package com.ecjtu.gateway.netty;


import com.alibaba.fastjson.JSONObject;
import com.ecjtu.gateway.db.po.LeakagePo;
import com.ecjtu.gateway.db.service.LeakageService;
import com.ecjtu.gateway.netty.model.DasDataModel;
import com.ecjtu.gateway.netty.model.PacketDataModel;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class NettyClient {

    @Autowired
    private LeakageService leakageService;

    @PostConstruct
    public void init() {

        try {
            EventLoopGroup group = new NioEventLoopGroup();
            // 开始try-catch块，用于捕获可能的异常
            Bootstrap bootstrap = new Bootstrap(); // 创建一个Bootstrap对象，它是Netty应用程序的入口点
            bootstrap.group(group) // 设置EventLoopGroup，用于处理I/O操作
                    .channel(NioSocketChannel.class) // 指定用于通信的Channel类型
                    .handler(new ChannelInitializer<SocketChannel>() { // 添加一个ChannelInitializer，用于初始化新连接的Channel
                        @Override // 覆盖ChannelInitializer中的初始化方法
                        protected void initChannel(SocketChannel ch) throws Exception { // 初始化Channel
                            ch.pipeline()
                                    .addLast(new NioEventLoopGroup(4),new NettyDecoder())
                                    .addLast(new NioEventLoopGroup(4),new NettyClientHandler(leakageService)); // 添加一个ClientHandler，用于处理业务逻辑
                        }
                    });

            Channel channel = bootstrap.connect("192.168.1.107", 7000).sync().channel();
        } catch (Exception e) {
            log.error("",e);
        }

    }
}

@Slf4j
 class NettyClientHandler extends SimpleChannelInboundHandler<PacketDataModel> {
    private LeakageService leakageService;
    public NettyClientHandler(LeakageService leakageService){
        this.leakageService = leakageService;
    }
    private OkHttpClient httpClient = new OkHttpClient();
     private final static String httpHeaderMediaType = "application/json;charset=utf-8";

     private final static String httpHeaderContentType = "Content-Type";
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PacketDataModel packetDataModel) throws Exception {
        //这里写发送和处理逻辑就好了
        doSendToPython(packetDataModel);
        log.info("here");
       
    }

    @Async
    private void doSaveToDb(JSONObject jsonObject) {
        LeakagePo leakagePo = new LeakagePo();
        leakagePo.setM(jsonObject.getString("m"));
        leakagePo.setTime(jsonObject.getString("time"));
        leakagePo.setData(jsonObject.getJSONArray("d").toJSONString());
        leakageService.save(leakagePo);
    }

    private void doSendToPython(PacketDataModel packetDataModel){
        JSONObject sendDataJson = new JSONObject();
        for(int i = 0; i < packetDataModel.getDasDataModel().getDataChannelCount()  ;i++){
            final  Integer compareIndex = i;
            List<Short> dataList = packetDataModel.getDasDataModel().getDetailDataList()
                    .stream().filter(detailData -> detailData.getChannelId().equals(compareIndex))
                    .map(DasDataModel.DetailData::getData)
                    .collect(Collectors.toList());
            sendDataJson.put("d",dataList);
            sendDataJson.put("m",(i+1));
            sendDataJson.put("time",new DateTime().toString("yyyy-MM-dd HH-mm-ss"));
            //doSaveToDb(sendDataJson);
            //

            RequestBody requestBody = RequestBody.create(MediaType.parse(httpHeaderMediaType), sendDataJson.toJSONString());
            Request request = new Request.Builder()
                    .addHeader(httpHeaderContentType, httpHeaderMediaType)
                    .addHeader("Accept", httpHeaderMediaType)
                    .post(requestBody)
                    .url("http://localhost:8888/data")
                    .build();
            Response signRsp = null;
            try {
                signRsp = httpClient.newCall(request).execute();
                if (signRsp.isSuccessful()) {
                }
            } catch (IOException e) {
                log.error("连接服务 失败", e);
            }

        }
    }
}
